package com.edu.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edu.entity.*;
import com.edu.mapper.*;
import com.edu.service.SubjectService;
import com.edu.service.UsersService;
import com.edu.vo.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.catalina.startup.UserConfig;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private MenusMapper menusMapper;

    @Autowired
    private StuUpInfoMapper stuUpInfoMapper;

    @Autowired
    private MajorMapper majorMapper;

    @Autowired
    private SchoolMapper schoolMapper;

    @Autowired
    private StuScoreMapper stuScoreMapper;

    @Autowired
    private SubjectMapper subjectMapper;
    @Autowired
    private StuInfoMapper stuInfoMapper;

    @Autowired
    private SubjectScoreMapper subjectScoreMapper;

    @Autowired
    private SubjectService subjectService;

    @Override
    public Result login(UsersLoginVo usersLoginVo) {
        QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
        if (usersLoginVo.getUsername().length() == 18) {
            //身份证号登录
            usersQueryWrapper.eq("id_card", usersLoginVo.getUsername());
        } else if (usersLoginVo.getUsername().length() == 11) {
            //手机号登录
            usersQueryWrapper.eq("phone", usersLoginVo.getUsername());
        } else {
            //长度不符合
            return Result.failure();
        }
        usersQueryWrapper.eq("password", usersLoginVo.getPassword());
        usersQueryWrapper.eq("role", usersLoginVo.getRole());
        List<Users> usersList = usersMapper.selectList(usersQueryWrapper);
        if (CollectionUtils.isEmpty(usersList)) {
            //用户信息不存在，登录失败
            return Result.failure();
        }
        //登录成功，返回用户信息
        return Result.success(usersList.get(0));
    }

    @Override
    public Result register(Users user) {
        //判断身份证或手机号是否已注册
        if (countByValue("id_card", user.getIdCard()) >= 1) {
            return Result.failure("", "该身份证已经注册！");
        }
        if (countByValue("phone", user.getPhone()) >= 1) {
            return Result.failure("", "该手机号已经注册！");
        }
        if (user.getRole() == null || user.getRole() == 0) {
            user.setRole(3);
        }
        usersMapper.insert(user);
        return Result.success("注册成功！");
    }

    /**
     * 通过查询某一字段为指定值的用户数量
     */
    private int countByValue(String key, Object value) {
        QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
        usersQueryWrapper.eq(key, value);
        List<Users> usersList = usersMapper.selectList(usersQueryWrapper);
        if (CollectionUtils.isEmpty(usersList)) {
            //用户信息不存在，
            return 0;
        }
        return usersList.size();
    }

    @Override
    public List<Menus> queryMenuList(Integer id) {
        return menusMapper.queryMenusList(id);
    }

    @Override
    public Result get(Long userId) {
        List<StudentVo> from = new ArrayList<>();
        List<StudentVo> to = new ArrayList<>();

        List<Users> list = new ArrayList<>();

        Users users = usersMapper.selectById(userId);
        Integer schoolId = users.getSchoolId();
        Integer role = users.getRole();
/*        //查询报考我校的学生
        QueryWrapper<StuUpInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("del_flag",0);
        if(role.equals(2)){
            wrapper.eq("school_id",schoolId);
        }
        wrapper.eq("up_year",new SimpleDateFormat("yyyy").format(new Date()));
        List<StuUpInfo> stuUpInfos = stuUpInfoMapper.selectList(wrapper);
        if(!CollectionUtils.isEmpty(stuUpInfos)){
            List<Long> idList = new ArrayList<>();
            stuUpInfos.forEach(x->{
                idList.add(x.getStuId());
            });
            List<Users> usersList = usersMapper.selectBatchIds(idList);
            list.addAll(usersList);
            usersList.forEach(x->{
                StudentVo studentVo = new StudentVo();
                BeanUtils.copyProperties(x,studentVo);
                to.add(studentVo);
            });
        }

        //查询我学校的学生
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role",3);
        queryWrapper.eq("del_flag",0);
        if(role.equals(2)){
            queryWrapper.eq("school_id",schoolId);
        }
        List<Users> usersList = usersMapper.selectList(queryWrapper);
        list.addAll(usersList);

        usersList.forEach(x->{
            StudentVo studentVo = new StudentVo();
            BeanUtils.copyProperties(x,studentVo);
            from.add(studentVo);
        });

        //填充学校，
        QueryWrapper<School> schoolQueryWrapper = new QueryWrapper<>();
        schoolQueryWrapper.eq("del_flag",0);
        List<School> schools = schoolMapper.selectList(schoolQueryWrapper);
        schools.forEach(school->{
            from.forEach(stu->{
                if(school.getId().equals(stu.getSchoolId())){
                    stu.setSchoolName(school.getName());
                    return;
                }
            });
            to.forEach(stu->{
                if(school.getId().equals(stu.getSchoolId())){
                    stu.setSchoolName(school.getName());
                    return;
                }
            });
        });
        //填充专业
        QueryWrapper<Major> majorQueryWrapper = new QueryWrapper<>();
        majorQueryWrapper.eq("del_flag",0);
        List<Major> majorList = majorMapper.selectList(majorQueryWrapper);
        majorList.forEach(major->{
            from.forEach(stu->{
                if(major.getId().equals(stu.getMajorId())){
                    stu.setMajorName(major.getName());
                    return;
                }
            });
            to.forEach(stu->{
                if(major.getId().equals(stu.getMajorId())){
                    stu.setMajorName(major.getName());
                    return;
                }
            });
        });
        //填充流程
        if(){

        }*/
        List<StudentVo> studentVoList = stuUpInfoMapper.selectAllStudent(users);
        //填充报考学校名
        QueryWrapper<School> schoolQueryWrapper = new QueryWrapper<>();
        schoolQueryWrapper.eq("del_flag", 0);
        List<School> schools = schoolMapper.selectList(schoolQueryWrapper);
        schools.forEach(school -> {
            studentVoList.forEach(stu -> {
                if (school.getId().equals(stu.getSchoolId())) {
                    stu.setSchoolName(school.getName());
                }
                if (stu.getToSchoolId() != null && school.getId().equals(stu.getToSchoolId())) {
                    stu.setToSchoolName(school.getName());
                }
            });
        });
        //填充专业
        QueryWrapper<Major> majorQueryWrapper = new QueryWrapper<>();
        majorQueryWrapper.eq("del_flag", 0);
        List<Major> majorList = majorMapper.selectList(majorQueryWrapper);
        majorList.forEach(major -> {
            studentVoList.forEach(stu -> {
                if (major.getId().equals(stu.getMajorId())) {
                    stu.setMajorName(major.getName());
                }
                if (stu.getToMajorId() != null && major.getId().equals(stu.getToMajorId())) {
                    stu.setToMajorName(major.getName());
                }
            });
        });
        //筛选我校 报考我校
        studentVoList.forEach(studentVo -> {
            if (role.intValue() == 2) {
                if (studentVo.getSchoolId().longValue() == schoolId.longValue()) {
                    from.add(studentVo);
                }
                if (studentVo.getToSchoolId().longValue() == schoolId.longValue()) {
                    to.add(studentVo);
                }
            } else if (role.intValue() == 1) {
                from.add(studentVo);
                to.add(studentVo);
            }

        });
        //返回
        HashMap<String, List<StudentVo>> map = new HashMap<>();
        map.put("fromMySchool", from);
        map.put("toMySchool", to);
        return Result.success(map);
    }

    @Override
    public Result addScore(StuScore stuScore) {
        if (stuScore.getStuId() == null) {
            stuScoreMapper.insert(stuScore);
        } else {
            stuScoreMapper.updateById(stuScore);
        }
        return Result.success();
    }

    @Override
    public Result deleteStuScore(Long id) {
        UpdateWrapper<StuScore> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("del_flag", 1);
        updateWrapper.eq("id", id);
        stuScoreMapper.update(null, updateWrapper);
        return Result.success();
    }

    @Override
    public Result selectScore(StuScoreVo stuScore) {

/*        QueryWrapper<StuScore> queryWrapper = new QueryWrapper<>();
        if (stuScore.getStuId() != null) {
            queryWrapper.eq("stu_id", stuScore.getStuId());
        }
        if (stuScore.getUpSchoolId() != null) {
            queryWrapper.eq("up_school_id", stuScore.getUpSchoolId());
        }
        if (stuScore.getUpMajorId() != null) {
            queryWrapper.eq("up_major_id", stuScore.getUpMajorId());
        }
        if (stuScore.getSubjectId() != null) {
            queryWrapper.eq("subject_id", stuScore.getSubjectId());
        }
        queryWrapper.eq("del_flag", 0);
        List<StuScore> scores = stuScoreMapper.selectList(queryWrapper);


        List<StuScoreVo> list = new ArrayList<>();
        Map<Long, List<StuScore>> listMap = scores.stream().collect(Collectors.groupingBy(score -> score.getStuId()));

        listMap.forEach((stu, scoreList) -> {
            StuScore score = scoreList.get(0);
            StuScoreVo stuScoreVo = new StuScoreVo();
            BeanUtils.copyProperties(score,stuScoreVo);
            HashMap<String, Integer> map = new HashMap<>();
            scoreList.forEach(x->{
                map.put(x.getSubjectId()+"",x.getScore());
            });
            int sum = scoreList.stream().mapToInt(x -> x.getScore()).sum();
            stuScoreVo.setScore(sum);
            stuScoreVo.setScoreMap(map);
            list.add(stuScoreVo);
        });


        //填充学生名
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("del_flag",0);
        List<Users> usersList = usersMapper.selectByMap(stringObjectHashMap);
        usersList.forEach(school -> {
            list.forEach(stu -> {
                if (school.getId().equals(stu.getStuId())) {
                    stu.setStuName(school.getName());
                }
            });
        });

        //填充报考学校名
        QueryWrapper<School> schoolQueryWrapper = new QueryWrapper<>();
        schoolQueryWrapper.eq("del_flag", 0);
        List<School> schools = schoolMapper.selectList(schoolQueryWrapper);
        schools.forEach(school -> {
            list.forEach(stu -> {
                if (school.getId().equals(stu.getUpSchoolId())) {
                    stu.setUpSchoolName(school.getName());
                }
            });
        });
        //填充学科
        QueryWrapper<SubjectScore> subjectQueryWrapper = new QueryWrapper<>();
        subjectQueryWrapper.eq("del_flag", 0);
        List<Subject> subjectList = subjectMapper.selectList(subjectQueryWrapper);
        list.forEach(stu -> {
            Map<String, Integer> scoreMap = stu.getScoreMap();
            Map<String, Integer> scoreMap1 = new HashMap<>();
            scoreMap.forEach((k, v) -> {
                subjectList.forEach(major -> {
                    if (major.getId().equals(Long.valueOf(k))) {
                        scoreMap1.put(major.getSubjectName(), v);
                    }
                });
            });
            stu.setScoreMap(scoreMap1);
        });*/


        //查询报考信息
        PageHelper.startPage(stuScore.getPageNum() != null ? stuScore.getPageNum() : 1
                , stuScore.getPageSize() != null ? stuScore.getPageSize() : 5);
        List<StuScoreVo> list = stuUpInfoMapper.selectStuUpInfo();
        PageInfo<StuScoreVo> pageInfo = new PageInfo<>(list);

        //查询报考专业下面的学科
        list.forEach(stu->{
            List<SubjectVo> result = subjectService.querySubjectScore(stu.getStuId(),stu.getToMajorId());
            Integer score =0;
            for (SubjectVo subjectVo:result) {

                score += subjectVo.getScore()!=null?subjectVo.getScore():0;
                if(subjectVo.getMinScore()==null){
                    subjectVo.setColor("green");
                }else if(subjectVo.getScore()==null || subjectVo.getScore()<=subjectVo.getMinScore()){
                    subjectVo.setColor("red");
                    stu.setColor("red");
                }
            }
            //总分
            stu.setScore(score);
            if(StringUtils.isBlank(stu.getColor()) ){
                stu.setColor("green");
            }
            //每个分数颜色
            stu.setSubjectVoList(result);

        });


        return Result.success(list,pageInfo.getTotal());
    }

    @Override
    public UserVo getUserInfo(Long id) {
        Users users = usersMapper.selectById(id);
        QueryWrapper<StuInfo> stuInfoQueryWrapper = new QueryWrapper<>();
        stuInfoQueryWrapper.eq("stu_id",id);
        StuInfo stuInfo = stuInfoMapper.selectOne(stuInfoQueryWrapper);
        QueryWrapper<StuUpInfo> stuUpInfoQueryWrapper = new QueryWrapper<>();
        stuUpInfoQueryWrapper.eq("stu_id",id);
        StuUpInfo stuUpInfo = stuUpInfoMapper.selectOne(stuUpInfoQueryWrapper);
        UserVo userVo = new UserVo(users,stuInfo, stuUpInfo);
        return userVo;
    }
}
